<?php
/**
 * Data Model
 *
 * @property Data $ParentData
 * @property Data $ChildData
 */
class Wechat extends WechatAppModel {

/**
 * Use table
 *
 * @var mixed False or table name
 */
	public $useTable = false;
	
	public function access_token(){
	    $token = Cache::read('CToken','token_');
	    if($token){
	      return $token;
	    }
	    $link = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential".
	    "&appid=".Configure::read("Wechat.appID").
	    "&secret=".Configure::read("Wechat.appsecret");
	    $return = $this->request($link);
	    $return = json_decode($return,true);
	    if(isset($return['access_token'])){
	        Cache::write('CToken',$return['access_token'],'token_');
	    }else{
	        var_dump($return);
	        exit;
	    }
	    return $return['access_token'];
	}
	
	public function jsapi_ticket(){
	    $ticket = Cache::read('jTicket','token_');
	    if($ticket){
	        return $ticket;
	    }
	    $CToken = $this->access_token();
	    $link = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$CToken&type=jsapi";
	    $jsapi = $this->request($link);
	    $jsapi = json_decode($jsapi,true);
	    if(isset($jsapi['ticket'])){
	        Cache::write('jTicket',$jsapi['ticket'],'token_');
	    }else{
	        var_dump($jsapi);
	        exit;
	    }
	    return $jsapi['ticket'];
	}
	
	public function jsApiConfig($jsApiList = array('chooseWXPay'),$url = false){
	    $jsapiTicket = $this->jsapi_ticket();
	    $nonceStr = 'zmx';
	    $timestamp = time();
	    if($url){
	    	$url = "http://".$_SERVER['HTTP_HOST']."/".substr(str_replace('/', '_', $_SERVER['REQUEST_URI']),1);
	    }else{
		    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    }
	    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	    $signature = sha1($string);
	    
	    $config = array(
	        'debug'=>false, //开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
	        'appId'=>Configure::read("Wechat.appID"), // 必填，公众号的唯一标识
	        'timestamp'=>$timestamp, // 必填，生成签名的时间戳
	        'nonceStr'=>$nonceStr, // 必填，生成签名的随机串
	        "url"=> $url,
	        "jt"=>$jsapiTicket,
	        'signature'=>$signature,// 必填，签名，见附录1
	        'jsApiList'=>$jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
	    );
	    return json_encode($config);
	}
	
}
